<template>
	<div class="container">
		<h2>{{ id ? '修改' : '创建' }}周转料租赁合同</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="saveContract">
			<a-row :gutter="20">
				<a-col :span="8">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="选择计划名称" name="plan_id" :rules="{ required: true, message: '请选择计划' }">
						<a-select v-model:value="formState.plan_id" :show-search="true" placeholder="请选择计划" :options="planlist" option-filter-prop="label" @change="choosePlan"></a-select>
					</a-form-item>
				</a-col>

				<a-col :span="8">
					<a-form-item label="合同名称" name="name" :rules="{ required: true, message: '请输入合同名称' }">
						<a-input v-model:value="formState.name" placeholder="请输入合同名称" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="合同编号" name="code" :rules="{ required: true, message: '请输入合同编号' }">
						<a-input v-model:value="formState.code" placeholder="请输入合同编号" @blur="checkCode" />
					</a-form-item>
				</a-col>

				<a-col :span="8">
					<a-form-item label="选择供应商名称" name="supplier_id" :rules="{ required: true, message: '请选择供应商' }">
						<a-select v-model:value="formState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="客户联系人" name="contact" :rules="{ required: true, message: '请输入客户联系人' }">
						<a-input v-model:value="formState.contact" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="签订时间" name="sign_time" :rules="{ required: true, message: '请输入签订时间' }">
						<a-date-picker v-model:value="formState.sign_time" :picker="date_type" value-format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-upload v-model:file-list="formState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
						<a-button>
							<template v-if="uploading">
								<loading-outlined />上传中...
							</template>
							<template v-else>
								<import-outlined />上传合同附件
							</template>
						</a-button>
					</a-upload>
				</a-col>

				<a-col :span="24">
					<h4>合同物资清单</h4>
					<div class="table-toolbar mb-3">
						<a-space>
							<a-button class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />暂存
							</a-button>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
						</a-space>
					</div>
					<a-table :scroll="tableScroll" :pagination="false" :data-source="formState.materials" :columns="planMaterialColumns1" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择周转料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择周转料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'model']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[record.key].model" :show-search="true" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'model', label: 'modelName' }" style="width:100%" @change="(model) => changeModel(record, model)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" :show-search="true" placeholder="请选择" :options="unitOptions[`${record.source_id}_${record.model}`] || []" :field-names="{ value: 'unit', label: 'unit' }" style="width:100%" @change="(unit) => changeMaterialUnit(record, unit, unitOptions[`${record.source_id}_${record.model}`])"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" @blur="checkqty(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{ required: true, message: '请输入计划租赁时长' }">
									<a-input-number v-model:value="formState.materials[index].use_time" placeholder="请输入计划租赁时长" @blur="checkqty(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{ required: true, message: '请选择时长计量单位' }">
									<a-select v-model:value="formState.materials[index].time_unit" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{ value: 'name' }" style="width:100%" disabled></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_subprice'">
								<a-form-item :name="['materials', index, 'without_tax_subprice']" :rules="{ required: true, message: '请输入不含税单价' }">
									<a-input-number v-model:value="formState.materials[index].without_tax_subprice" placeholder="请输入不含税单价" @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_amount'">
								<a-form-item :name="['materials', index, 'without_tax_amount']" :rules="{ required: true, message: '请输入不含税总价' }">
									<a-input-number v-model:value="formState.materials[index].without_tax_amount" placeholder="请输入不含税总价" @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'tax'">
								<a-form-item :name="['materials', index, 'tax']" :rules="{ required: true, message: '请输入税率' }">
									<a-input-number v-model:value="formState.materials[index].tax" placeholder="请输入税率" @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'with_tax_subprice'">
								<a-form-item :name="['materials', index, 'with_tax_subprice']" :rules="{ required: true, message: '请输入含税单价' }">
									<a-input-number v-model:value="formState.materials[index].with_tax_subprice" placeholder="请输入含税单价" @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'with_tax_amount'">
								<a-form-item :name="['materials', index, 'with_tax_amount']" :rules="{ required: true, message: '请输入含税总价' }">
									<a-input-number v-model:value="formState.materials[index].with_tax_amount" placeholder="请输入含税总价" @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'tax_amount'">
								<a-form-item :name="['materials', index, 'tax_amount']">
									<a-input v-model:value="formState.materials[index].tax_amount" placeholder="税额" disabled @blur="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
						<template #summary>
							<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
								<a-table-summary-cell :col-span="2">
									<a-typography-text type="danger">合计</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell :col-span="6"></a-table-summary-cell>

								<a-table-summary-cell>
									<a-typography-text>{{ formState.amount }}</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell>
									<a-typography-text>{{ formState.with_tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell>
									<a-typography-text>{{ formState.tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
							</a-table-summary-row>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>
						<a-button v-if="!formState.id || ![-1,0,1,2].includes(formState.workflow_status)" type="primary" html-type="submit">
							<save-outlined />保存
						</a-button>
						<a-workflow v-if="formState.id" v-model:status="formState.workflow_status" module="contractzz" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.opr_id" @submit="submitPurchase"></a-workflow>
						<a-button @click="closeTab('/contractzz')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { DeleteOutlined, SaveOutlined, DeliveredProcedureOutlined, CloseOutlined, LoadingOutlined, ImportOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { baseURL } from "../utils/request";
//import dayjs from "dayjs";
import { post, listToTree, postJson } from "../utils";
import { useRoute } from "vue-router";
import { subtract } from "@/utils/operation.js";
import { AWorkflow } from "@/components/index.js";
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const formState = ref({ materials: [] });
const planlist = ref([]); //	计划列表
const userlist = ref([]); // 供应商列表
const uploading = ref(false);
const formRef = ref();
const timeunitOptions = ref([]);
const { proxy } = getCurrentInstance();
const handleCache = () => {
	// console.log(formState.value);
	localStorage.setItem("contractzz-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};

const addMaterialModel = () => {
	if (!formState.value.name || !formState.value.code || !formState.value.plan_id || !formState.value.supplier_id || !formState.value.contact) {
		proxy.$message.error("请将基本信息填写完善再录入物资清单");
		return;
	}
	formState.value.materials.push({ key: formState.value.materials.length });
};
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
post("dictionary", { root_code: "MATERIAL_TIMEUNIT" }).then(data => {
	timeunitOptions.value = data;
});
const planMaterialColumns1 = [
	{
		title: "ID",
		dataIndex: "key",
		width: 60,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + 1;
		}
	},
	{
		title: "周转料名称",
		dataIndex: "name",
		width: 250,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 130,
		ellipsis: true
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "需用数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "计划租赁时长",
		dataIndex: "use_time",
		width: 100,
		align: "center"
	},
	{
		title: "时长单位",
		dataIndex: "time_unit",
		width: 100,
		align: "center"
	},
	{
		title: "不含税单价(元)",
		dataIndex: "without_tax_subprice",
		width: 120,
		align: "center"
	},
	{
		title: "不含税总价(元)",
		dataIndex: "without_tax_amount",
		width: 120,
		align: "center"
	},
	{
		title: "税率%",
		dataIndex: "tax",
		width: 120,
		align: "center"
	},
	{
		title: "含税单价(元)",
		dataIndex: "with_tax_subprice",
		width: 120,
		align: "center"
	},
	{
		title: "含税总价(元)",
		dataIndex: "with_tax_amount",
		width: 120,
		align: "center"
	},
	{
		title: "税额",
		dataIndex: "tax_amount",
		width: 120,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];
const unitOptions = ref([]);
const checkCode = async () => {
	if (!formState.value.code) return;
	post("contract/check/code", { code: formState.value.code, id: id.value }).catch(err => {
		proxy.$message.error(err);
		formState.value.code = null;
	});
}
const checkqty = async record => {
	if (record.id > 0) {
		//当前的物资数量
		let current_qty = 0;
		formState.value.materials.map(d => {
			if (d.id === record.id) {
				current_qty = current_qty + parseFloat(d.quantity);
			}
		});
		let current_use_time = 0;
		formState.value.materials.map(d => {
			if (d.id === record.id) {
				current_use_time = current_use_time + parseFloat(d.use_time);
			}
		});
		const contractHistory = await post("contract/all", { plan_id: formState.value.plan_id });
		const history_current_qty = contractHistory.reduce((target, item) => {
			if (parseInt(item.id) === parseInt(route.params.id)) return target;
			for (const material of item.materials) {
				if (material.id !== record.id) {
					continue;
				}
				target = target + parseFloat(material.ContractMaterial.quantity);
			}
			return target;
		}, 0);
		post("contract/plan_num_all", { plan_id: formState.value.plan_id, material_id: record.id }).then(data => {
			if (current_qty > data.quantity - history_current_qty) {
				proxy.$message.error("合同清单数量不能超过计划数量");
				let now_qty = parseFloat(data.quantity) - parseFloat(history_current_qty) - parseFloat(current_qty) + parseFloat(record.quantity);
				if (now_qty < 0) {
					now_qty = 0;
				}
				formState.value.materials[record.key]["quantity"] = now_qty;
			}

			if (current_use_time > data.use_time) {
				proxy.$message.error("合同清单时长不能超过计划时长");
				let now_qty = parseFloat(data.use_time) - parseFloat(current_use_time) + parseFloat(record.use_time);
				if (now_qty < 0) {
					now_qty = 0;
				}
				formState.value.materials[record.key]["use_time"] = now_qty;
			}
			calAmount();
		});
	} else {
		proxy.$message.error("请先选择物资");
		formState.value.materials[record.key]["quantity"] = "";
	}
};

onMounted(async () => {
	const cacheData = localStorage.getItem("contractzz-save");
	formState.value = JSON.parse(cacheData) || formState.value;
	if (id.value) {
		const { plan_id, project_id } = await post("contract/info", { id: id.value }).then(data => {
			data.file_path = JSON.parse(data.file_path || "[]");
			let amount = 0;
			let wt_amount = 0;
			let t_amount = 0;

			data.materials = data.materials.map((d, i) => {
				d.key = i;

				const { unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, with_tax_subprice, with_tax_amount, tax_amount, tax, standard, add_time, use_time, time_unit, useto, memo } = d.ContractMaterial;
				d.unit = unit;
				d.quantity = quantity;
				d.without_tax_subprice_base = without_tax_subprice_base;
				d.down_per = down_per;
				d.up_per = up_per;
				d.without_tax_subprice = without_tax_subprice;
				d.without_tax_amount = without_tax_amount;
				d.tax = tax;
				d.with_tax_subprice = with_tax_subprice;
				d.with_tax_amount = with_tax_amount;
				d.tax_amount = tax_amount;

				d.standard = standard;
				d.add_time = add_time;
				d.use_time = use_time;
				d.time_unit = time_unit;
				d.useto = useto;
				d.memo = memo;
				wt_amount = parseFloat(wt_amount) + parseFloat(with_tax_amount);
				amount = parseFloat(amount) + parseFloat(without_tax_amount);
				t_amount = parseFloat(t_amount) + parseFloat(tax_amount);

				return d;
			});

			formState.value = data;
			formState.value.with_tax_amount = wt_amount.toFixed(2);
			formState.value.tax_amount = t_amount.toFixed(2);

			return data;
		});
	} else {
		formState.value.type = 1;
	}

	const { project_id, plan_id } = formState.value;
	if (project_id) {
		await post("plan", { type: 2, page_size: Infinity, project_id, workflow_status: 2 }).then(({ data }) => {
			planlist.value = data.map(d => {
				return {
					value: d.id,
					label: d.name
				};
			});
		});
	}

	if (plan_id) {
		await post("dictionary", { plan_id, workflow_status: 2 }).then(data => {
			materialOptions.value = data;
		});
	}

	post("user", { is_supplier: 1, page_size: Infinity, status: 1 }).then(({ data }) => {
		userlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.company_name || d.mobile
			};
		});
	});
});
const projectOptions = ref([]);
post("department/projects?type=3", { page_size: 1000 }).then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
//选择项目对应的计划
const changeProject = value => {
	const project_id = value;
	post("plan", { type: 2, project_id: project_id }).then(({ data }) => {
		planlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
};
const choosePlan = value => {
	const plan_id = value;
	formState.value.plan_id = plan_id;
	formState.value.materials = []; //清空物资清单
	post("dictionary", { plan_id, workflow_status: 2 }).then(data => {
		//	const { root_id: rootId } = data[0] || {};
		materialOptions.value = data;
		//获取所有规格
		post("material", { source_id: data.map(d => d.id).join(","), plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
			materialModelOptions.value = (() => {
				const array = [];
				data.forEach(d => {
					if (!array[d.source_id]) array[d.source_id] = [];

					if (d.attr) d.model = `${d.model}（${d.attr}）`;

					array[d.source_id].push(d);
				});

				return array;
			})(data);
		});
	});

	post("plan/info", { id: value }).then(data => {
		formState.value.type = data.type;
	});
};

//上传前校验
const beforeUpload = file => {
	uploading.value = true;
	if (file.type !== "application/pdf") {
		proxy.$message.error("只能上传PDF文件");
		uploading.value = false;

		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		uploading.value = false;
		return false;
	}
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		uploading.value = false;
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
	}
};
//计算总额
const calAmount = () => {
	let amount = 0;
	let with_tax_amount = 0;
	let tax_amount = 0;

	formState.value.materials.map(d => {
		/*
		if (!d.id || d.id === 0) {
			d.quantity = 0;
			d.without_tax_subprice_base = 0;
			d.without_tax_subprice = 0;
			d.down_per = 0;
			d.up_per = 0;
			d.without_tax_amount = 0;
			d.use_time = 0;
		}
		d.quantity = d.quantity ? d.quantity : 0;
		d.without_tax_subprice_base = d.without_tax_subprice_base ? d.without_tax_subprice_base : 0;
		d.without_tax_subprice = d.without_tax_subprice ? d.without_tax_subprice : 0;
		d.down_per = d.down_per ? d.down_per : 0;
		d.up_per = d.up_per ? d.up_per : 0;
		d.use_time = d.use_time ? d.use_time : 0;
		d.tax = d.tax ? d.tax : 0;
		d.with_tax_subprice = d.with_tax_subprice ? d.with_tax_subprice : 0;
		d.with_tax_amount = d.with_tax_amount ? d.with_tax_amount : 0;

		d.quantity = parseFloat(d.quantity);
		d.without_tax_subprice_base = parseFloat(d.without_tax_subprice_base);
		d.without_tax_subprice = parseFloat(d.without_tax_subprice);
		d.down_per = parseFloat(d.down_per);
		d.up_per = parseFloat(d.up_per);
		d.use_time = parseInt(d.use_time);
		d.tax = parseFloat(d.tax);
		d.with_tax_subprice = parseInt(d.with_tax_subprice);
		d.with_tax_amount = parseInt(d.with_tax_amount);

		if (d.quantity <= 0) {
			d.quantity = 0;
		}
		if (d.without_tax_subprice_base && d.without_tax_subprice_base > 0) {
			if (d.down_per > 0) {
				d.without_tax_subprice = (d.without_tax_subprice_base * (100 - d.down_per)) / 100;
			} else if (d.up_per > 0) {
				d.without_tax_subprice = (d.without_tax_subprice_base * (100 + d.up_per)) / 100;
			} else {
				d.without_tax_subprice = d.without_tax_subprice_base;
			}
			d.without_tax_subprice = Number.parseFloat(d.without_tax_subprice).toFixed(2);
		}
		if (d.tax >= 0) {
			//固定价格 计算含税单价及含税总价 含税单价等于不含税单价加上（不含税单价×税率）
			d.with_tax_subprice = d.without_tax_subprice * (1 + d.tax / 100);
			d.with_tax_subprice = Number.parseFloat(d.with_tax_subprice).toFixed(2);
		}

		if (d.use_time > 0) {
			d.without_tax_amount = d.without_tax_subprice * d.use_time * d.quantity;
			d.with_tax_amount = d.with_tax_subprice * d.use_time * d.quantity;
		} else {
			d.without_tax_amount = d.without_tax_subprice * d.quantity;
			d.with_tax_amount = d.with_tax_subprice * d.quantity;
		}
		d.without_tax_amount = Number.parseFloat(d.without_tax_amount).toFixed(2);
		d.with_tax_amount = Number.parseFloat(d.with_tax_amount).toFixed(2);
		d.tax_amount = d.with_tax_amount - d.without_tax_amount;
		d.tax_amount = Number.parseFloat(d.tax_amount).toFixed(2);
		if (d.tax_amount < 0) {
			d.tax_amount = 0;
		}
		*/
		const formatColumn = ["quantity", "use_time", "with_tax_subprice", "with_tax_amount", "without_tax_subprice", "without_tax_amount"];
		for (const key of formatColumn) {
			if (!d[key] || parseFloat(d[key]) === 0 || d[key] < 0) {
				d[key] = null;
			} else {
				d[key] = parseFloat(d[key] || 0).toFixed(2);
			}
		}
		if (d.with_tax_subprice && d.without_tax_subprice && parseFloat(d.with_tax_subprice) < parseFloat(d.without_tax_subprice)) {
			proxy.$message.error("含税单价不能小于不含税单价");
			d.with_tax_subprice = null;
		}
		if (d.with_tax_amount && d.without_tax_amount && parseFloat(d.with_tax_amount) < parseFloat(d.without_tax_amount)) {
			proxy.$message.error("含税总价不能小于不含税总价");
			d.with_tax_amount = null;
		}
		if (d.with_tax_amount && d.without_tax_amount) {
			d.tax_amount = subtract([d.with_tax_amount, d.without_tax_amount]);
		}
		// d.quantity = parseFloat(d.quantity || 0).toFixed(2);
		// d.use_time = parseFloat(d.use_time || 0).toFixed(2);
		//
		// d.without_tax_subprice_base = parseFloat(d.without_tax_subprice_base || 0).toFixed(2);
		// d.tax = parseFloat(d.tax || 0).toFixed(2);
		// d.tax_amount = parseFloat(d.tax_amount || 0).toFixed(2);

		amount += parseFloat(d.without_tax_amount || 0);
		with_tax_amount += parseFloat(d.with_tax_amount || 0);
		tax_amount += parseFloat(d.tax_amount || 0);
	});

	formState.value.amount = parseFloat(amount).toFixed(2);
	formState.value.with_tax_amount = parseFloat(with_tax_amount).toFixed(2);
	formState.value.tax_amount = parseFloat(tax_amount).toFixed(2);
};
const saveContract = () => {
	localStorage.removeItem("contractzz-save");
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			params.file_path = JSON.stringify(params.file_path);
			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			params.materials = JSON.stringify(
				params.materials.map(({ id, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, tax, with_tax_subprice, with_tax_amount, tax_amount, standard, add_time, use_time, time_unit, useto, memo }) => {
					return {
						id,
						unit,
						quantity,
						without_tax_subprice_base,
						down_per,
						up_per,
						without_tax_subprice,
						without_tax_amount,
						tax,
						with_tax_subprice,
						with_tax_amount,
						tax_amount,
						standard,
						add_time,
						use_time,
						time_unit,
						useto,
						memo
					};
				})
			);

			postJson("contract/save", params)
				.then(() => {
					if (id.value) {
						proxy.$message.success("合同修改成功", 1);
					} else {
						proxy.$message.success("合同创建成功", 1);
					}

					closeTab("/contractZZ");
					localStorage.removeItem("contractzz-save");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

const materialOptions = ref([]);

post("dictionary", { root_id: "57" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: Infinity, plan_id: formState.value.plan_id, workflow_status: 2 }).then(({ data }) => {
		const modelNameOpts = {};
		const selectListOpts = {};
		for (const d of data) {
			if (!modelNameOpts[d.source_id]) modelNameOpts[d.source_id] = [];
			if (!selectListOpts[d.source_id]) selectListOpts[d.source_id] = [];
			const modelName = d.attr ? `${d.model}（${d.attr}）` : d.model;
			if (modelNameOpts[d.source_id].includes(modelName)) continue;
			modelNameOpts[d.source_id].push(modelName);
			selectListOpts[d.source_id].push({
				model: d.model,
				modelName: modelName
			});
		}
		for (const key in selectListOpts) {
			materialModelOptions.value[key] = selectListOpts[key];
		}
		unitOptions.value = [];
		for (const material of formState.value.materials) {
			const units = [];
			for (const d of data) {
				if (d.source_id === material.source_id && d.model === material.model) {
					units.push(d);
				}
			}
			unitOptions.value[`${material.source_id}_${material.model}`] = units;
		}
	});
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;
	record.model = null;
	record.unit = null;

	if (!id) return;

	post("material", { source_id: id, plan_id: formState.value.plan_id, page_size: Infinity }).then(({ data }) => {
		const modelNames = [];
		const selectList = [];
		for (const d of data) {
			const modelName = d.attr ? `${d.model}（${d.attr}）` : d.model;
			if (modelNames.includes(modelName)) continue;
			modelNames.push(modelName);
			selectList.push({
				model: d.model,
				modelName: modelName
			});
		}
		materialModelOptions.value[id] = selectList;
	});
};

const changeModel = (record, model) => {
	record.id = null;
	record.unit = null;
	if (!unitOptions.value[`${record.source_id}_${record.model}`]) {
		post("material", { source_id: record.source_id, plan_id: formState.value.plan_id, page_size: Infinity }).then(({ data }) => {
			const selectList = [];
			for (const d of data) {
				if (d.model !== model) {
					continue;
				}
				selectList.push(d);
			}
			unitOptions.value[`${record.source_id}_${record.model}`] = selectList;
		});
	}
};
const changeMaterialUnit = (record, unit, unitOpt) => {
	const material = unitOpt.filter(item => item.unit === unit)[0];
	record.id = material.id;
	if (formState.value.materials.filter(d => d.id === record.id).length > 1) {
		record.id = null;
		record.unit = null;
		return proxy.$message.error("该物料规格已存在合同列表，请选择其他规格或物料");
	}
	if (formState.value.materials[record.key]["quantity"] > 0) {
		checkqty(record);
	}
	// 补充时长单位
	post("contract/plan_material_info", { plan_id: formState.value.plan_id, material_id: record.id }).then(data => {
		formState.value.materials[record.key]["time_unit"] = data[0]?.time_unit || null;
	});
	post("price", { material_id: material.id }).then(({ data, total }) => {
		if (total > 0) {
			const { price } = data[0];
			//赋值给基准价
			formState.value.materials.map(d => {
				d.without_tax_subprice_base = 0;
				d.without_tax_subprice_base_disabled = "";
				if (d.id === material.id) {
					d.without_tax_subprice_base = price;
					d.without_tax_subprice_base_disabled = true;
				}
				return d;
			});
		} else {
			formState.value.materials.map(d => {
				if (d.id === material.id) {
					d.without_tax_subprice_base = 0;
					d.without_tax_subprice_base_disabled = false;
				}
				return d;
			});
		}
	});
};
/**
const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
}; */

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
};
const submitPurchase = () => {
	proxy.$message.success("合同提交成功", 1);
	closeTab("/contractzz");
};
//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
